import * as types from '../_types/lastPrice';
import { IReduxLastPrice } from '../interface';

interface IState{
    [key: string]: Array<IReduxLastPrice>,
}

const MAX_LAST_PRICE_LENGTH = 10;


export default function updateLastPrice(state:IState = {}, action) {
    const {type, payload} = action;
    switch(type) {
        case types.INSERT_LAST_PRICE: {
            const {coinType, lastPrice: data} : {coinType: string, lastPrice: IReduxLastPrice} = payload;
            let lastPriceArr = state[coinType];
            if (!lastPriceArr || !lastPriceArr.length) {
                lastPriceArr = [data,];
            } else {
                let index = lastPriceArr.findIndex(v => v.timestamp === data.timestamp);
                if (index == -1) {
                    if (lastPriceArr.length >= MAX_LAST_PRICE_LENGTH) {
                        lastPriceArr = lastPriceArr.slice(1, MAX_LAST_PRICE_LENGTH);
                    }
                    lastPriceArr.push(data);
                }
            }
            state[coinType] = lastPriceArr;
            return state;
        }
        default:{
            return state;
        }
    }
}